from datetime import datetime, timedelta

from django.utils import timezone
from rest_framework.exceptions import ValidationError

from apps.core.utils import date_time as datetime_helper


def validate_access_granted(appointment, value):
    if appointment is None:
        return value
    booking = appointment.booking

    if appointment.access_granted and value:
        raise ValidationError('Access already granted')

    start_datetime = timezone.make_aware((datetime.combine(booking.start_date.date(), booking.start_time)),
                                         timezone.get_current_timezone()) - timedelta(minutes=15)
    end_datetime = timezone.make_aware((datetime.combine(booking.start_date.date(), booking.end_time)),
                                       timezone.get_current_timezone())

    now = datetime_helper.now()
    if now < start_datetime or now > end_datetime:
        raise ValidationError('Invalid grant access time')

    return value